package www.woniuxy.com.class112.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;
import com.aliyun.oss.internal.OSSUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
//import www.woniuxy.com.class112.dao.UserIdentityMapper;
//import www.woniuxy.com.class112.dao.UserRoleMapper;
//import www.woniuxy.com.class112.entity.UserIdentity;
//import www.woniuxy.com.class112.entity.UserRole;
//import www.woniuxy.com.class112.param.*;
//import www.woniuxy.com.class112.dao.UserInfosMapper;
//import www.woniuxy.com.class112.entity.UserInfos;
//import www.woniuxy.com.class112.entity.UserInfosExample;
import org.springframework.web.multipart.MultipartFile;
import www.woniuxy.com.class112.dao.TechnologyTypeMapper;
import www.woniuxy.com.class112.dao.UserIdentityMapper;
import www.woniuxy.com.class112.dao.UserInfosMapper;
import www.woniuxy.com.class112.dao.UserRoleMapper;
import www.woniuxy.com.class112.dto.QueryUserInformationDto;
import www.woniuxy.com.class112.entity.*;
import www.woniuxy.com.class112.param.AdminRegistrationParam;
import www.woniuxy.com.class112.param.ModifyUserInformationParam;
import www.woniuxy.com.class112.param.userInfo.*;
import www.woniuxy.com.class112.service.UserInfoService;
import www.woniuxy.com.class112.util.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private AliyunOSSUtil ossUtil;
    @Resource
    private UserInfosMapper userInfoMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TechnologyTypeMapper technologyTypeMapper;

    @Resource
    private UserIdentityMapper userIdentityMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private SMSUtil smsUtil;
    @Override
    public UserInfos userLogin(UserLoginParam param) throws Exception {
//        System.out.println(param);
        UserInfosExample userInfoExample = new UserInfosExample();
        UserInfosExample.Criteria c = userInfoExample.createCriteria();
        c.andUserNameEqualTo(param.getUsername());
        c.andUserStatrEqualTo(0L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(userInfoExample);
        if(userInfos==null||userInfos.size()==0){
            throw new Exception("用户不存在");
        }
//        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_USER.longValue()){
//            throw new Exception("当前登录者不是用户，无法登录");
//        }
        if (!MD5Util.md5(param.getPassword(),param.getUsername()).equals(userInfos.get(0).getPassword())){
            throw new Exception("密码错误");
        }
        return userInfos.get(0);
    }

    @Override
    public void adminRegistration(AdminRegistrationParam param) throws Exception {
        UserInfosExample userInfoExample = new UserInfosExample();
        UserInfosExample.Criteria c = userInfoExample.createCriteria();
        c.andUserNameEqualTo(param.getUsername());
        c.andUserStatrEqualTo(0L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(userInfoExample);
        if (userInfos.size()==0||userInfos==null){
            String userPass = MD5Util.md5(param.getPassword(), param.getUsername());
//            UserInfos userInfos1 = new UserInfos();
            UserInfos userInfos2 = BeanUtil.toBean(param, UserInfos.class);
            userInfos2.setPassword(userPass);
            long workerId = 1;
            long datacenterId = 1;
            // 创建 SnowflakeIdGeneratorUtil 实例
            SnowflakeIdGeneratorUtil idGenerator = new SnowflakeIdGeneratorUtil(workerId, datacenterId);
            // 生成唯一的 ID
            long userId = idGenerator.nextId();
            userInfos2.setUserId(userId);
            userInfos2.setRoleId(4L);
            userInfos2.setTechnologyId(1L);
            userInfos2.setUserStatr(0L);
            userInfos2.setUserName(param.getUsername());
            userInfoMapper.insert(userInfos2);
        }else {
            throw new Exception("用户名已存在，请重新输入");
        }
    }

    @Override
    public void LoginVerificationCode(String phone) throws Exception {
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(phone).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos==null||userInfos.isEmpty()){
                throw new Exception("手机号未被注册，无法登录");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_USER.longValue()){
            throw new Exception("当前登录者不是用户，无法发送验证码");
        }
//        String code = smsUtil.sendCode(phone);
        redisUtil.set(RedisKeyUtil.USER_INFO_LOGIN(phone),"1234",5*60);
    }

    @Override
    public UserInfos loginWithPhoneNumber(LoginUserInfoCodeParam param) throws Exception {
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(param.getPhone()).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos==null||userInfos.isEmpty()){
            throw new Exception("手机号未被注册，无法登录");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_USER.longValue()){
            throw new Exception("当前登录者不是用户，无法登录");
        }
        String code = redisUtil.get(RedisKeyUtil.USER_INFO_LOGIN(param.getPhone()));
        if (!param.getCode().equals(code)){
            throw new Exception("验证码错误，请重新输入");
        }
        return userInfos.get(0);
    }

    @Override
    public void registrationVerificationCode(String phone) throws Exception {
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(phone).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        System.out.println(userInfos);
        if (userInfos!=null&&!userInfos.isEmpty()){
            throw new Exception("手机号已被注册");
        }
//        String code = smsUtil.sendCode(phone);
        redisUtil.set(RedisKeyUtil.USER_INFO_REGISTER(phone),"1234",5*60);
    }

    @Override
    public void userMobileNumberRegistration(RegisterUserInfoCodeParam param) throws Exception {
//        UserIdentity userIdentity = userIdentityMapper.selectByPrimaryKey((int) param.getIdentityId().longValue());
//        if (userIdentity==null){
//            throw new Exception("类别不存在");
//        }
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(param.getPhone()).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos!=null&&!userInfos.isEmpty()){
            throw new Exception("手机号已被注册，无法注册");
        }
        String code = redisUtil.get(RedisKeyUtil.USER_INFO_REGISTER(param.getPhone()));
        if (!param.getCode().equals(code)){
            throw new Exception("验证码错误，请重新输入");
        }
        UserInfosExample e1 = new UserInfosExample();
        e1.createCriteria().andUserNameEqualTo(param.getUsername()).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos1 = userInfoMapper.selectByExample(e1);
        if (userInfos1!=null&&!userInfos1.isEmpty()){
            throw new Exception("用户名重复，无法注册");
        }
        UserInfos userInfos2 = new UserInfos();
        userInfos2.setRoleId(Properties.ROLE_USER);
        userInfos2.setUserName(param.getUsername());
        String userPass = MD5Util.md5(param.getPassword(), param.getUsername());
        userInfos2.setPassword(userPass);
        userInfos2.setPhone(param.getPhone());
        userInfos2.setUserStatr(0L);
        userInfos2.setTechnologyId(param.getIdentityId());
        userInfoMapper.insert(userInfos2);
        UserInfosExample e2 = new UserInfosExample();
        e2.createCriteria().andUserNameEqualTo(userInfos2.getUserName());
        List<UserInfos> userInfos3 = userInfoMapper.selectByExample(e2);
        UserRole userRole = new UserRole();
        userRole.setUserId(userInfos3.get(0).getId());
        userRole.setRoleId(Properties.ROLE_USER);
        userRoleMapper.insert(userRole);
    }

    @Override
    public UserInfos superAdminLogin(UserLoginParam param) throws Exception {
        System.out.println(param);
        UserInfosExample userInfoExample = new UserInfosExample();
        UserInfosExample.Criteria c = userInfoExample.createCriteria();
        c.andUserNameEqualTo(param.getUsername());
        c.andUserStatrEqualTo(0L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(userInfoExample);
        if(userInfos==null||userInfos.size()==0){
            throw new Exception("基层工作人员不存在");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_SUPER_ADMIN.longValue()){
            throw new Exception("当前登录者不是基层工作人员，无法登录");
        }
        if (!MD5Util.md5(param.getPassword(),param.getUsername()).equals(userInfos.get(0).getPassword())){
            throw new Exception("密码错误");
        }
        return userInfos.get(0);
    }

    @Override
    public void superAdminVerificationCodeSending(String phone) throws Exception {
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(phone).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos==null||userInfos.isEmpty()){
            throw new Exception("手机号未被注册，无法登录");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_SUPER_ADMIN.longValue()){
            throw new Exception("当前登录者不是基层工作人员，无法发送验证码");
        }
        String code = smsUtil.sendCode(phone);
        redisUtil.set(RedisKeyUtil.SUPER_ADMIN_LOGIN(phone),code,5*60);
    }

    @Override
    public UserInfos agentLogin(UserLoginParam param) throws Exception {
        UserInfosExample userInfoExample = new UserInfosExample();
        UserInfosExample.Criteria c = userInfoExample.createCriteria();
        c.andUserNameEqualTo(param.getUsername());
        c.andUserStatrEqualTo(0L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(userInfoExample);
        if(userInfos==null||userInfos.size()==0){
            throw new Exception("特派员不存在");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_AGENT.longValue()){
            throw new Exception("当前登录者不是特派员，无法登录");
        }
        if (!MD5Util.md5(param.getPassword(),param.getUsername()).equals(userInfos.get(0).getPassword())){
            throw new Exception("密码错误");
        }
        return userInfos.get(0);
    }

    @Override
    public UserInfos superAdminLoginCode(LoginUserInfoCodeParam param) throws Exception {
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(param.getPhone()).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos==null||userInfos.isEmpty()){
            throw new Exception("手机号未被注册，无法登录");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_SUPER_ADMIN.longValue()){
            throw new Exception("当前登录者不是基层工作人员，无法登录");
        }
        String code = redisUtil.get(RedisKeyUtil.SUPER_ADMIN_LOGIN(param.getPhone()));
        if (!param.getCode().equals(code)){
            throw new Exception("验证码错误，请重新输入");
        }
        return userInfos.get(0);
    }

    @Override
    public void agentLoginCodeSending(String phone) throws Exception {
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(phone).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos==null||userInfos.isEmpty()){
            throw new Exception("手机号未被注册，无法登录");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_AGENT.longValue()){
            throw new Exception("当前登录者不是特派员，无法发送验证码");
        }
        String code = smsUtil.sendCode(phone);
        redisUtil.set(RedisKeyUtil.AGENT_LOGIN(phone),code,5*60);
    }

    @Override
    public UserInfos agentLoginCode(LoginUserInfoCodeParam param) throws Exception {
        UserInfosExample e = new UserInfosExample();
        e.createCriteria().andPhoneEqualTo(param.getPhone()).andUserStatrNotEqualTo(2L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos==null||userInfos.isEmpty()){
            throw new Exception("手机号未被注册，无法登录");
        }
        if(userInfos.get(0).getRoleId().longValue()!=Properties.ROLE_AGENT.longValue()){
            throw new Exception("当前登录者不是特派员，无法登录");
        }
        String code = redisUtil.get(RedisKeyUtil.AGENT_LOGIN(param.getPhone()));
        if (!param.getCode().equals(code)){
            throw new Exception("验证码错误，请重新输入");
        }
        return userInfos.get(0);
    }

    @Override
    public UserInfos adminLogin(UserLoginParam toBean) throws Exception {
        UserInfosExample example = new UserInfosExample();
        example.createCriteria().andUserNameEqualTo(toBean.getUsername()).andRoleIdEqualTo(Properties.ROLE_ADMIN);
        //根据账号找出管理员
        List<UserInfos> userInfos = userInfoMapper.selectByExample(example);
        //判断管理员账户是否存在
        if (userInfos==null||userInfos.isEmpty()){
            throw new RuntimeException("管理员账号不存在");
        }
        if (userInfos.get(0).getUserStatr()!=0){
            throw new RuntimeException("管理员账号状态异常");
        }
        //判断管理员密码是否正确
        if (!MD5Util.md5(toBean.getPassword(),toBean.getUsername()).equals(userInfos.get(0).getPassword())){
            throw new RuntimeException("密码错误");
        }
        return userInfos.get(0);
    }

    @Override
    public List<UserInfos> selectUser() {
        UserInfosExample e = new UserInfosExample();
        UserInfosExample.Criteria criteria = e.createCriteria();
        criteria.andRoleIdEqualTo(Properties.ROLE_USER);
        criteria.andUserStatrEqualTo(0L);
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        System.out.println(userInfos);
        return userInfos;
    }

    @Override
    public PageInfo<UserInfos> selectAdminAccout(SelectAdminAccoutParam param) {
        Page<UserInfos> page = PageHelper.startPage(param.getPageIndex()==null?1:param.getPageIndex(), param.getPageSize()==null?5:param.getPageSize());
        UserInfosExample e = new UserInfosExample();
        UserInfosExample.Criteria criteria = e.createCriteria();
        criteria.andRoleIdEqualTo(Properties.ROLE_ADMIN);
        criteria.andUserStatrNotEqualTo(2L);
        if (param.getUsername()!=null){
            criteria.andUserNameLike("%"+param.getUsername()+"%");
        }
        userInfoMapper.selectByExample(e);
        return new PageInfo<UserInfos>(page);
    }

    @Override
    public void delistAccout(Long id) throws Exception {
        UserInfos userInfos = userInfoMapper.selectByPrimaryKey(id);
        if (userInfos==null){
            throw new Exception("管理员不存在");
        }
        if (userInfos.getUserStatr()!=0){
            throw new Exception("管理员状态异常");
        }
        userInfos.setUserStatr(1L);
        userInfoMapper.updateByPrimaryKeySelective(userInfos);
    }

    @Override
    public void enableAccout(Long id) throws Exception {
        UserInfos userInfos = userInfoMapper.selectByPrimaryKey(id);
        if (userInfos==null){
            throw new Exception("管理员不存在");
        }
        if (userInfos.getUserStatr()!=1){
            throw new Exception("管理员状态异常");
        }
        userInfos.setUserStatr(0L);
        userInfoMapper.updateByPrimaryKeySelective(userInfos);
    }

    @Override
    public void deleteAccout(Long id) throws Exception {
        UserInfos userInfos = userInfoMapper.selectByPrimaryKey(id);
        if (userInfos==null){
            throw new Exception("管理员不存在");
        }
        if (userInfos.getUserStatr()==2){
            throw new Exception("管理员状态异常");
        }
        userInfos.setUserStatr(2L);
        userInfoMapper.updateByPrimaryKeySelective(userInfos);
    }

    @Override
    public void addAdminAccout(AddAccoutParam param) throws Exception {
        UserInfosExample e = new UserInfosExample();
        UserInfosExample.Criteria criteria = e.createCriteria();
        criteria.andUserStatrNotEqualTo(2L);
        criteria.andRoleIdEqualTo(Properties.ROLE_ADMIN);
        criteria.andUserNameEqualTo(param.getUserName());
        List<UserInfos> userInfos = userInfoMapper.selectByExample(e);
        if (userInfos!=null&&!userInfos.isEmpty()){
            throw new RuntimeException("管理员账号已存在");
        }
        UserInfosExample e1 = new UserInfosExample();
        UserInfosExample.Criteria criteria1 = e1.createCriteria();
        criteria1.andUserStatrNotEqualTo(2L);
        criteria1.andRoleIdEqualTo(Properties.ROLE_ADMIN);
        criteria1.andPhoneEqualTo(param.getPhone());
        List<UserInfos> userInfos1 = userInfoMapper.selectByExample(e);
        if (userInfos1!=null&&!userInfos1.isEmpty()){
            throw new RuntimeException("手机号已存在");
        }
        UserInfos userInfos2 = new UserInfos();
        userInfos2.setUserName(param.getUserName());
        userInfos2.setPassword(MD5Util.md5(param.getPassWord(),param.getUserName()));
        userInfos2.setPhone(param.getPhone());
        userInfos2.setRoleId(Properties.ROLE_ADMIN);
        userInfos2.setUserStatr(0L);
        userInfoMapper.insertSelective(userInfos2);
    }

    @Override
    public QueryUserInformationDto queryUserInformation(Long userId) {
        UserInfos userInfos = userInfoMapper.selectByPrimaryKey(userId);
        QueryUserInformationDto dto = BeanUtil.toBean(userInfos, QueryUserInformationDto.class);
        TechnologyType technologyType = technologyTypeMapper.selectByPrimaryKey(dto.getTechnologyId());
        dto.setTechnologyTypeName(technologyType.getTechnologyName());
        dto.setUserGenderName((dto.getUserGender() != null && dto.getUserGender().longValue() == 1) ? "男" : (dto.getUserGender() != null && dto.getUserGender().longValue() == 1)?"女":"保密");
        return dto;
    }

    @Override
    public void modifyUserInformation(ModifyUserInformationParam param, Long userId) throws Exception {
        UserInfos userInfos = BeanUtil.toBean(param, UserInfos.class);
        userInfos.setUserGender(param.getUserGenderName().equals("男")?1L:param.getUserGenderName().equals("女")?2L:3L);
        userInfos.setId(userId);
        userInfoMapper.updateByPrimaryKeySelective(userInfos);
    }

    @Override
    public void updateProfilePicture(MultipartFile file, Long userId) throws Exception {
        String type = FileTypeUtil.getType(file.getInputStream());
        if (!"jpg".equals(type)&&!"png".equals(type)){
            throw new Exception("文件类型错误");
        }
        String name = file.getOriginalFilename();
        String substring = name.substring(name.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+ substring;
        String imageUrl = ossUtil.uploadFile(file.getInputStream(), fileName, "amour520");
        System.out.println(imageUrl);
        UserInfos userInfos = userInfoMapper.selectByPrimaryKey(userId);
        userInfos.setPictureUrl(imageUrl);
        userInfoMapper.updateByPrimaryKeySelective(userInfos);
    }

    @Override
    public String searchForProfilePicture(Long userId) {
        UserInfos userInfos = userInfoMapper.selectByPrimaryKey(userId);
        return userInfos.getPictureUrl();
    }

}
